<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>管理员仪表板 - 工单管理系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.min.css" rel="stylesheet">
    <style>
        :root {
            --admin-primary: #dc3545;
            --admin-secondary: #6c757d;
            --sidebar-width: 250px;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: #f8f9fa;
        }

        .sidebar {
            position: fixed;
            top: 0;
            left: 0;
            height: 100vh;
            width: var(--sidebar-width);
            background: linear-gradient(180deg, var(--admin-primary) 0%, #c82333 100%);
            color: white;
            z-index: 1000;
            transition: all 0.3s ease;
        }

        .sidebar.collapsed {
            width: 70px;
        }

        .sidebar-header {
            padding: 20px;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
            text-align: center;
        }

        .sidebar-header h4 {
            margin: 0;
            font-weight: 600;
        }

        .sidebar-header .collapse-btn {
            position: absolute;
            top: 20px;
            right: 15px;
            background: none;
            border: none;
            color: white;
            font-size: 18px;
            cursor: pointer;
        }

        .sidebar-menu {
            padding: 20px 0;
        }

        .menu-item {
            display: flex;
            align-items: center;
            padding: 12px 20px;
            color: rgba(255, 255, 255, 0.8);
            text-decoration: none;
            transition: all 0.3s ease;
            border-left: 3px solid transparent;
        }

        .menu-item:hover {
            background: rgba(255, 255, 255, 0.1);
            color: white;
            border-left-color: white;
        }

        .menu-item.active {
            background: rgba(255, 255, 255, 0.15);
            color: white;
            border-left-color: white;
        }

        .menu-item i {
            width: 20px;
            margin-right: 12px;
            text-align: center;
        }

        .menu-text {
            transition: opacity 0.3s ease;
        }

        .sidebar.collapsed .menu-text {
            opacity: 0;
            width: 0;
        }

        .main-content {
            margin-left: var(--sidebar-width);
            min-height: 100vh;
            transition: all 0.3s ease;
        }

        .sidebar.collapsed + .main-content {
            margin-left: 70px;
        }

        .top-navbar {
            background: white;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            padding: 15px 30px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .user-info {
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .user-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: var(--admin-primary);
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: 600;
        }

        .content-area {
            padding: 30px;
        }

        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }

        .stat-card {
            background: white;
            border-radius: 15px;
            padding: 25px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            border-left: 4px solid var(--admin-primary);
            transition: transform 0.3s ease;
        }

        .stat-card:hover {
            transform: translateY(-5px);
        }

        .stat-card h3 {
            font-size: 2.5rem;
            font-weight: 700;
            margin: 0;
            color: var(--admin-primary);
        }

        .stat-card p {
            margin: 5px 0 0 0;
            color: #6c757d;
            font-weight: 500;
        }

        .stat-card i {
            font-size: 2rem;
            color: var(--admin-primary);
            margin-bottom: 15px;
        }

        .chart-container {
            background: white;
            border-radius: 15px;
            padding: 25px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            margin-bottom: 30px;
            position: relative;
        }

        .chart-title {
            font-size: 1.5rem;
            font-weight: 600;
            margin-bottom: 20px;
            color: #333;
        }

        .chart-error {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            height: 300px;
            color: #6c757d;
            text-align: center;
        }

        .chart-error i {
            font-size: 3rem;
            margin-bottom: 1rem;
            color: #ffc107;
        }

        .chart-error p {
            margin: 0;
            font-size: 1.1rem;
        }

        .recent-activity {
            background: white;
            border-radius: 15px;
            padding: 25px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }

        .activity-item {
            display: flex;
            align-items: center;
            padding: 15px 0;
            border-bottom: 1px solid #f1f3f4;
        }

        .activity-item:last-child {
            border-bottom: none;
        }

        .activity-icon {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 15px;
            font-size: 16px;
        }

        .activity-icon.ticket {
            background: #e3f2fd;
            color: #1976d2;
        }

        .activity-icon.feedback {
            background: #f3e5f5;
            color: #7b1fa2;
        }

        .activity-icon.user {
            background: #e8f5e8;
            color: #388e3c;
        }

        .activity-content h6 {
            margin: 0 0 5px 0;
            font-weight: 600;
        }

        .activity-content small {
            color: #6c757d;
        }

        .btn-admin {
            background: var(--admin-primary);
            border-color: var(--admin-primary);
            color: white;
        }

        .btn-admin:hover {
            background: #c82333;
            border-color: #c82333;
            color: white;
        }

        @media (max-width: 768px) {
            .sidebar {
                transform: translateX(-100%);
            }

            .sidebar.show {
                transform: translateX(0);
            }

            .main-content {
                margin-left: 0;
            }

            .stats-grid {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>
    <!-- 侧边栏 -->
    <div class="sidebar" id="sidebar">
        <div class="sidebar-header">
            <h4><i class="fas fa-crown me-2"></i><span class="menu-text">管理员面板</span></h4>
            <button class="collapse-btn" onclick="toggleSidebar()">
                <i class="fas fa-bars"></i>
            </button>
        </div>
        <nav class="sidebar-menu">
            <a href="#" class="menu-item active" data-section="dashboard">
                <i class="fas fa-tachometer-alt"></i>
                <span class="menu-text">仪表板</span>
            </a>
            <a href="#" class="menu-item" data-section="users">
                <i class="fas fa-users"></i>
                <span class="menu-text">用户管理</span>
            </a>
            <a href="#" class="menu-item" data-section="tickets">
                <i class="fas fa-ticket-alt"></i>
                <span class="menu-text">工单管理</span>
            </a>
            <a href="#" class="menu-item" data-section="feedbacks">
                <i class="fas fa-comments"></i>
                <span class="menu-text">反馈管理</span>
            </a>
            <a href="#" class="menu-item" data-section="statistics">
                <i class="fas fa-chart-bar"></i>
                <span class="menu-text">统计分析</span>
            </a>
            <a href="#" class="menu-item" data-section="settings">
                <i class="fas fa-cog"></i>
                <span class="menu-text">系统设置</span>
            </a>
            <a href="#" class="menu-item" data-section="logs">
                <i class="fas fa-file-alt"></i>
                <span class="menu-text">系统日志</span>
            </a>
        </nav>
    </div>

    <!-- 主内容区 -->
    <div class="main-content">
        <!-- 顶部导航栏 -->
        <div class="top-navbar">
            <div>
                <button class="btn btn-outline-secondary d-md-none" onclick="toggleSidebar()">
                    <i class="fas fa-bars"></i>
                </button>
                <h5 class="mb-0 d-none d-md-inline">管理员控制台</h5>
            </div>
            <div class="user-info">
                <div class="dropdown">
                    <button class="btn btn-outline-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown">
                        <div class="user-avatar" id="userAvatar">A</div>
                        <span class="ms-2" id="userName">管理员</span>
                    </button>
                    <ul class="dropdown-menu dropdown-menu-end">
                        <li><a class="dropdown-item" href="#" onclick="showProfile()">
                            <i class="fas fa-user me-2"></i>个人资料
                        </a></li>
                        <li><a class="dropdown-item" href="#" onclick="showSettings()">
                            <i class="fas fa-cog me-2"></i>设置
                        </a></li>
                        <li><hr class="dropdown-divider"></li>
                        <li><a class="dropdown-item" href="#" onclick="logout()">
                            <i class="fas fa-sign-out-alt me-2"></i>退出登录
                        </a></li>
                    </ul>
                </div>
            </div>
        </div>

        <!-- 内容区域 -->
        <div class="content-area">
            <!-- 仪表板概览 -->
            <div id="dashboard-section">
                <h2 class="mb-4">系统概览</h2>
                
                <!-- 统计卡片 -->
                <div class="stats-grid">
                    <div class="stat-card">
                        <i class="fas fa-users"></i>
                        <h3 id="totalUsers">0</h3>
                        <p>总用户数</p>
                    </div>
                    <div class="stat-card">
                        <i class="fas fa-ticket-alt"></i>
                        <h3 id="totalTickets">0</h3>
                        <p>总工单数</p>
                    </div>
                    <div class="stat-card">
                        <i class="fas fa-comments"></i>
                        <h3 id="totalFeedbacks">0</h3>
                        <p>总反馈数</p>
                    </div>
                    <div class="stat-card">
                        <i class="fas fa-clock"></i>
                        <h3 id="pendingTickets">0</h3>
                        <p>待处理工单</p>
                    </div>
                </div>

                <!-- 图表区域 -->
                <div class="row">
                    <div class="col-lg-8">
                        <div class="chart-container">
                            <h5 class="chart-title">工单趋势分析</h5>
                            <canvas id="ticketTrendChart"></canvas>
                        </div>
                    </div>
                    <div class="col-lg-4">
                        <div class="chart-container">
                            <h5 class="chart-title">工单状态分布</h5>
                            <canvas id="ticketStatusChart"></canvas>
                        </div>
                    </div>
                </div>

                <!-- 最近活动 -->
                <div class="recent-activity">
                    <h5 class="chart-title">最近活动</h5>
                    <div id="recentActivities">
                        <!-- 动态加载活动列表 -->
                    </div>
                </div>
            </div>

            <!-- 其他页面内容将在这里动态加载 -->
            <div id="other-sections" style="display: none;">
                <!-- 用户管理、工单管理等内容 -->
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.min.js"></script>
    <script>
        // 全局变量
        const API_BASE_URL = 'http://localhost:9090/api';
        let currentUser = null;
        let ticketTrendChart = null;
        let ticketStatusChart = null;

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', async () => {
            // 检查登录状态
            if (!await checkAuth()) {
                window.location.href = 'login.html';
                return;
            }

            // 加载用户信息
            await loadUserInfo();
            
            // 加载仪表板数据
            await loadDashboardData();
            
            // 初始化图表
            initCharts();
            
            // 绑定菜单事件
            bindMenuEvents();
        });

        // 检查认证状态
        async function checkAuth() {
            const token = localStorage.getItem('token');
            if (!token) return false;

            try {
                const response = await fetch(`${API_BASE_URL}/auth/me`, {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });

                if (response.ok) {
                    const data = await response.json();
                    if (data.success && data.data.role === 'ADMIN') {
                        currentUser = data.data;
                        return true;
                    }
                }
            } catch (error) {
                console.error('认证检查失败:', error);
            }

            return false;
        }

        // 加载用户信息
        async function loadUserInfo() {
            if (currentUser) {
                document.getElementById('userName').textContent = currentUser.fullName || currentUser.username;
                document.getElementById('userAvatar').textContent = (currentUser.fullName || currentUser.username).charAt(0).toUpperCase();
            }
        }

        // 加载仪表板数据
        async function loadDashboardData() {
            try {
                // 获取系统概览数据
                const response = await fetch(`${API_BASE_URL}/statistics/overview`, {
                    headers: {
                        'Authorization': `Bearer ${localStorage.getItem('token')}`
                    }
                });
                
                if (response.ok) {
                    const result = await response.json();
                    const data = result.data;
                    
                    // 更新统计卡片
                    document.getElementById('totalUsers').textContent = data.users?.totalUsers || '0';
                    document.getElementById('totalTickets').textContent = data.tickets?.totalTickets || '0';
                    document.getElementById('totalFeedbacks').textContent = data.feedbacks?.totalFeedbacks || '0';
                    document.getElementById('pendingTickets').textContent = data.tickets?.statusStats?.OPEN || '0';
                } else {
                    // 如果API调用失败，使用模拟数据
                    console.warn('API调用失败，使用模拟数据');
                    document.getElementById('totalUsers').textContent = '1,234';
                    document.getElementById('totalTickets').textContent = '5,678';
                    document.getElementById('totalFeedbacks').textContent = '2,345';
                    document.getElementById('pendingTickets').textContent = '89';
                }

                // 加载最近活动
                loadRecentActivities();
            } catch (error) {
                console.error('加载仪表板数据失败:', error);
                // 使用模拟数据作为后备
                document.getElementById('totalUsers').textContent = '1,234';
                document.getElementById('totalTickets').textContent = '5,678';
                document.getElementById('totalFeedbacks').textContent = '2,345';
                document.getElementById('pendingTickets').textContent = '89';
                loadRecentActivities();
            }
        }

        // 加载最近活动
        function loadRecentActivities() {
            const activities = [
                {
                    icon: 'ticket',
                    iconClass: 'fas fa-ticket-alt',
                    title: '新工单 #1234',
                    description: '客户张三提交了新的工单',
                    time: '2分钟前'
                },
                {
                    icon: 'feedback',
                    iconClass: 'fas fa-comments',
                    title: '新反馈',
                    description: '客户李四对工单 #1230 进行了反馈',
                    time: '15分钟前'
                },
                {
                    icon: 'user',
                    iconClass: 'fas fa-user-plus',
                    title: '新用户注册',
                    description: '王五注册了新的客户账户',
                    time: '1小时前'
                },
                {
                    icon: 'ticket',
                    iconClass: 'fas fa-check-circle',
                    title: '工单已解决',
                    description: '工单 #1228 已被客服人员解决',
                    time: '2小时前'
                }
            ];

            const container = document.getElementById('recentActivities');
            container.innerHTML = activities.map(activity => `
                <div class="activity-item">
                    <div class="activity-icon ${activity.icon}">
                        <i class="${activity.iconClass}"></i>
                    </div>
                    <div class="activity-content">
                        <h6>${activity.title}</h6>
                        <small>${activity.description} · ${activity.time}</small>
                    </div>
                </div>
            `).join('');
        }

        // 初始化图表
        async function initCharts() {
            try {
                await initTicketTrendChart();
                await initTicketStatusChart();
            } catch (error) {
                console.error('初始化图表失败:', error);
                // 显示错误信息
                showChartError();
            }
        }

        // 初始化工单趋势图
        async function initTicketTrendChart() {
            try {
                const response = await fetch(`${API_BASE_URL}/statistics/charts/ticket-trend`, {
                    headers: {
                        'Authorization': `Bearer ${localStorage.getItem('token')}`
                    }
                });
                
                let chartData;
                if (response.ok) {
                    const result = await response.json();
                    chartData = result.data;
                } else {
                    // 使用模拟数据
                    chartData = {
                        labels: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
                        datasets: [{
                            label: '新建工单',
                            data: [12, 19, 3, 5, 2, 3, 7],
                            borderColor: '#dc3545',
                            backgroundColor: 'rgba(220, 53, 69, 0.1)',
                            tension: 0.4
                        }, {
                            label: '已解决工单',
                            data: [8, 15, 5, 8, 3, 5, 9],
                            borderColor: '#28a745',
                            backgroundColor: 'rgba(40, 167, 69, 0.1)',
                            tension: 0.4
                        }]
                    };
                }

                const trendCtx = document.getElementById('ticketTrendChart').getContext('2d');
                ticketTrendChart = new Chart(trendCtx, {
                    type: 'line',
                    data: chartData,
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                            legend: {
                                position: 'top',
                            }
                        },
                        scales: {
                            y: {
                                beginAtZero: true
                            }
                        }
                    }
                });
            } catch (error) {
                console.error('初始化工单趋势图失败:', error);
                throw error;
            }
        }

        // 初始化工单状态分布图
        async function initTicketStatusChart() {
            try {
                const response = await fetch(`${API_BASE_URL}/statistics/charts/ticket-status`, {
                    headers: {
                        'Authorization': `Bearer ${localStorage.getItem('token')}`
                    }
                });
                
                let chartData;
                if (response.ok) {
                    const result = await response.json();
                    chartData = result.data;
                } else {
                    // 使用模拟数据
                    chartData = {
                        labels: ['待处理', '处理中', '已解决', '已关闭'],
                        datasets: [{
                            data: [30, 25, 35, 10],
                            backgroundColor: [
                                '#ffc107',
                                '#17a2b8',
                                '#28a745',
                                '#6c757d'
                            ]
                        }]
                    };
                }

                const statusCtx = document.getElementById('ticketStatusChart').getContext('2d');
                ticketStatusChart = new Chart(statusCtx, {
                    type: 'doughnut',
                    data: chartData,
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                            legend: {
                                position: 'bottom',
                            }
                        }
                    }
                });
            } catch (error) {
                console.error('初始化工单状态分布图失败:', error);
                throw error;
            }
        }

        // 显示图表错误信息
        function showChartError() {
            const trendContainer = document.querySelector('#ticketTrendChart').parentElement;
            trendContainer.innerHTML = `
                <div class="chart-error">
                    <i class="fas fa-exclamation-triangle"></i>
                    <p>图表加载失败，请检查网络连接或刷新页面重试</p>
                </div>
            `;
        }

        // 绑定菜单事件
        function bindMenuEvents() {
            const menuItems = document.querySelectorAll('.menu-item');
            menuItems.forEach(item => {
                item.addEventListener('click', (e) => {
                    e.preventDefault();
                    
                    // 移除所有活动状态
                    menuItems.forEach(mi => mi.classList.remove('active'));
                    // 添加当前活动状态
                    item.classList.add('active');
                    
                    // 处理菜单切换
                    const section = item.dataset.section;
                    handleMenuClick(section);
                });
            });
        }

        // 处理菜单点击
        function handleMenuClick(section) {
            // 这里可以根据不同的section加载不同的内容
            console.log('切换到:', section);
            
            if (section === 'dashboard') {
                document.getElementById('dashboard-section').style.display = 'block';
                document.getElementById('other-sections').style.display = 'none';
            } else {
                document.getElementById('dashboard-section').style.display = 'none';
                document.getElementById('other-sections').style.display = 'block';
                // 加载对应页面内容
                loadPageContent(section);
            }
        }

        // 加载页面内容
        function loadPageContent(section) {
            const container = document.getElementById('other-sections');
            container.innerHTML = `<h2>${getSectionTitle(section)}</h2><p>此功能正在开发中...</p>`;
        }

        // 获取页面标题
        function getSectionTitle(section) {
            const titles = {
                'users': '用户管理',
                'tickets': '工单管理',
                'feedbacks': '反馈管理',
                'statistics': '统计分析',
                'settings': '系统设置',
                'logs': '系统日志'
            };
            return titles[section] || '未知页面';
        }

        // 切换侧边栏
        function toggleSidebar() {
            const sidebar = document.getElementById('sidebar');
            sidebar.classList.toggle('collapsed');
        }

        // 显示个人资料
        function showProfile() {
            alert('个人资料功能正在开发中...');
        }

        // 显示设置
        function showSettings() {
            alert('设置功能正在开发中...');
        }

        // 退出登录
        function logout() {
            if (confirm('确定要退出登录吗？')) {
                localStorage.clear();
                window.location.href = 'login.html';
            }
        }
    </script>
</body>
</html>
